<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: 子弹兄  Date:2019-03-08 Time:15:39
// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\model\airquality\AirQualityWeatherForecastDay;
use app\common\model\airquality\AirQualityWeatherRealtimeDay;
use app\common\service\airquality\AirQualityService;
use think\Db;
use think\Exception;
use think\facade\Config;

header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

/**
 * 首页的API
 */
class Index extends BaseController
{
    // +----------------------------------------------------------------------
    // | 目录
    // | 注意：方法统一用英文，驼峰式
    // | 1.0-0 空气质量示例 airQualityDemo
    // +----------------------------------------------------------------------

    /**
     * 1.0-1 历史六天和今天天气情况
     * @author zhugeng 2018-03-21
     */
//     public function airAllQualityWeather(){
//         $nowDate = date("Y-m-d");//获取当天primary_pollutant_name日期
//         $param = $this->request->param();
// //        $nowDate = '2019-04-19';
//         $param['station_id'] = 1;//长治市内站点选择（暂时为1）
//         $param['region_id'] = 53;
// //        if (empty($param['date_time']) || empty($param['station_id']) || empty($param['region_id'])) {
// //            return $this->error('参数错误!');
// //        }
//         //根据今天日期算出本周7天日期
//         $date = self::get_week(time());
//         $todayIndex = array_search($nowDate,$date);//今天日期所在位置索引
// //        for ($i = 1;$i < 8;$i++) {
// //            if ($date[$i] == date("Y-m-d",time())) {
// //                if ($i == 6) {
// //
// //                }
// //                $todayIndex = $i;
// //            }
// //        }
//         //今天之前查询实际值  今天和今天之后查询预报值
//         if ($todayIndex == 1) {
//             $strsql = 'predict_time between '.$date[1].' and '.$date[7];
//             $sqlnew1 = 'select predict_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_forecast_day where region_id = ? and '.$strsql;
//             $sqlnew2 = 'select predict_time as dt_time,aqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and '.$strsql;
//             $sqlnew3 = 'select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strsql;
//             $resultNew1 = Db::query($sqlnew1,array($param['region_id']));
//             $resultNew2 = Db::query($sqlnew2,array($param['region_id'],$param['station_id']));
//             $resultNew3 = Db::query($sqlnew3,array($param['region_id'],$param['station_id']));
//         } else if ($todayIndex == 7) {
//             $strold = 'publish_time between '.$date[1].' and '.$date[6];
//             $sqlold1 = 'select publish_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_realtime_day where region_id = ? and '.$strold;
//             $sqlold2 = 'select publish_time as dt_time,aqi from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and '.$strold;
//             $sqlold3 = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strold;
//             $strnew = 'predict_time = '.$date[7];
//             $sqlnew1 = 'select predict_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_forecast_day where region_id = ? and '.$strnew;
//             $sqlnew2 = 'select predict_time as dt_time,aqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $sqlnew3 = 'select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $resultOld1 = Db::query($sqlold1,array($param['region_id']));
//             $resultOld2 = Db::query($sqlold2,array($param['region_id'],$param['station_id']));
//             $resultOld3 = Db::query($sqlold3,array($param['region_id'],$param['station_id']));
//             $resultNew1 = Db::query($sqlnew1,array($param['region_id']));
//             $resultNew2 = Db::query($sqlnew2,array($param['region_id'],$param['station_id']));
//             $resultNew3 = Db::query($sqlnew3,array($param['region_id'],$param['station_id']));
//         } else if ($todayIndex == 2) {
//             $strold = 'publish_time = '.$date[1];
//             $sqlold1 = 'select publish_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_realtime_day where region_id = ? and '.$strold;
//             $sqlold2 = 'select publish_time as dt_time,aqi from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and '.$strold;
//             $sqlold3 = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strold;
//             $strnew = 'predict_time between '.$date[2].' and '.$date[6];
//             $sqlnew1 = 'select predict_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_forecast_day where region_id = ? and '.$strnew;
//             $sqlnew2 = 'select predict_time as dt_time,aqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $sqlnew3 = 'select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $resultOld1 = Db::query($sqlold1,array($param['region_id']));
//             $resultOld2 = Db::query($sqlold2,array($param['region_id'],$param['station_id']));
//             $resultOld3 = Db::query($sqlold3,array($param['region_id'],$param['station_id']));
//             $resultNew1 = Db::query($sqlnew1,array($param['region_id']));
//             $resultNew2 = Db::query($sqlnew2,array($param['region_id'],$param['station_id']));
//             $resultNew3 = Db::query($sqlnew3,array($param['region_id'],$param['station_id']));
//         } else {
//             $strold = 'publish_time between '.$date[1].' and '.$date[$todayIndex-1];
//             $sqlold1 = 'select publish_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_realtime_day where region_id = ? and '.$strold;
//             $sqlold2 = 'select publish_time as dt_time,aqi from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and '.$strold;
//             $sqlold3 = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strold;
//             $strnew = 'predict_time between '.$date[$todayIndex].' and '.$date[7];
//             $sqlnew1 = 'select predict_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_forecast_day where region_id = ? and '.$strnew;
//             $sqlnew2 = 'select predict_time as dt_time,aqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $sqlnew3 = 'select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and '.$strnew;
//             $resultOld1 = Db::query($sqlold1,$param['region_id']);
//             $resultOld2 = Db::query($sqlold2,array($param['region_id'],$param['station_id']));
//             $resultOld3 = Db::query($sqlold3,array($param['region_id'],$param['station_id']));
//             $resultNew1 = Db::query($sqlnew1,array($param['region_id']));
//             $resultNew2 = Db::query($sqlnew2,array($param['region_id'],$param['station_id']));
//             $resultNew3 = Db::query($sqlnew3,array($param['region_id'],$param['station_id']));
//         }
//         //历史日期范围（不包括今天）
// //        $oldStartDate = $date[1];
// //        $oldEndDate = $date[$todayIndex-1];
// //        $newStartDate = $date[1];
// //        $newEndDate = $date[7];
// //
// //        $sqlold1 = 'select publish_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_realtime_day where region_id = ? and publish_time between ? and ?';
// //        $sqlold2 = 'select publish_time as dt_time,aqi from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
// //        $sqlold3 = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and publish_time between ? and ?';
// //
// //        $sqlnew1 = 'select predict_time as dt_time,maximum_temperature,minimum_temperature,average_temperature,average_wind,wind_direction,average_humidity,average_sky_condition from air_quality_weather_forecast_day where region_id = ? and predict_time between ? and ?';
// //        $sqlnew2 = 'select predict_time as dt_time,aqi from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?';
// //        $sqlnew3 = 'select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?';
//
//
//
// //        if (count($resultOld1) <= 0 || count($resultOld2) <= 0 || count($resultOld3) <= 0 || count($resultNew1) <= 0 || count($resultNew2) <= 0 || count($resultNew3) <= 0) {
// //            return $this->error('暂无数据');
// //        }
//         $data = [];
//         foreach ($date as $k => $v) {
//             $data[$v] = [];
//             if ($k < $todayIndex) {
//                 $oldarr1 = [];
//                 $oldarr2 = [];
//                 $oldarr3 = [];
//                 if (isset($resultOld1) && !empty($resultOld1)) {
//                     foreach ($resultOld1 as $k1 => $v1) {
//                         if ($date[$k] == substr($v1['dt_time'],0,10)) {
//                             $oldarr1 = $v1;
//                         }
//                     }
//                 }
//                 if (isset($resultOld2) && !empty($resultOld2)) {
//                     foreach ($resultOld2 as $k2 => $v2) {
//                         if ($date[$k] == substr($v2['dt_time'],0,10)) {
//                             $oldarr2 = $v2;
//                         }
//                     }
//                 }
//                 if (isset($resultOld3) && !empty($resultOld3)) {
//                     foreach ($resultOld3 as $k3 => $v3) {
//                         if ($date[$k] == substr($v3['dt_time'],0,10)) {
//                             $oldarr3['first'] = $v3;
//                         }
//                     }
//                 }
//
//                 $oldDate = [ 'year'=>date("Y",strtotime($v)), 'month'=>date("m",strtotime($v)), 'day'=>date("d",strtotime($v))];
//                 $data[$v] = array_merge($oldarr1,$oldarr2,$oldarr3,$oldDate);
//             } else {
//                 $newarr1 = [];
//                 $newarr2 = [];
//                 $newarr3 = [];
//                 if (isset($resultNew1) && !empty($resultNew1)) {
//                     foreach ($resultNew1 as $k11 => $v11) {
//                         if ($date[$k] == substr($v11['dt_time'],0,10)) {
//                             $newarr1 = $v11;
//                         }
//                     }
//                 }
//                 if (isset($resultNew2) && !empty($resultNew2)) {
//                     foreach ($resultNew2 as $k22 => $v22) {
//                         if ($date[$k] == substr($v22['dt_time'],0,10)) {
//                             $newarr2 = $v22;
//                         }
//                     }
//                 }
//                 if (isset($resultNew3) && !empty($resultNew3)) {
//                     foreach ($resultNew3 as $k33 => $v33) {
//                         if ($date[$k] == substr($v33['dt_time'],0,10)) {
//                             $newarr3['first'] = $v33;
//                         }
//                     }
//                 }
//                 $newDates = [
//                     'date'=>['year'=>date("Y",strtotime($v)), 'month'=>date("m",strtotime($v)), 'day'=>date("d",strtotime($v))],
//                     'indicator'=>[
//                         ['name'=>'最高气温','max'=>100],
//                         ['name'=>'最低气温','max'=>100],
//                         ['name'=>'AQI','max'=>100],
//                         ['name'=>'湿度','max'=>100],
//                         ['name'=>'首要污染物','max'=>100],
//                         ['name'=>'风力','max'=>100],
//                     ]
//                 ];
//                 $data[$v] = array_merge($newarr1,$newarr2,$newarr3,$newDates);
//             }
//         }
//         $dataValue = [];
//         foreach ($data as $k => $v) {
//             array_push($dataValue,$v['maximum_temperature']);
//             array_push($dataValue,$v['minimum_temperature']);
//             array_push($dataValue,$v['aqi']);
//             array_push($dataValue,$v['average_humidity']);
//             if (count($v['first']) > 1) {
//                 $namePollutant = [];
//                 $valuePollutant = [];
//                 foreach ($v['first'] as $kj => $vj) {
//                     array_push($namePollutant,$vj['name']);
//                     array_push($valuePollutant,$vj['value']);
//                 }
//                 array_push($dataValue,implode($valuePollutant));
//             }
//             array_push($dataValue,$v['average_wind']);
//         }
// //        $data = array();
//         //日期处理
// //        $data['weather'] = $result1[0]['average_sky_condition'];//天气阴晴
// //        $data['wind_direction'] = $result1[0]['wind_direction'];//风向
// //        $data['indicator'] = array(
// //            array('name'=>'最高气温','max'=>100),
// //            array('name'=>'风力','max'=>100),
// //            array('name'=>$result3[0]['name'],'max'=>100),
// //            array('name'=>'湿度','max'=>100),
// //            array('name'=>'AQI','max'=>100),
// //            array('name'=>'最低气温','max'=>100),
// //        );
// //        $data['data'] = [$result1[0]['maximum_temperature'],$result1[0]['average_wind'],$result3[0]['value'],$result1[0]['average_humidity'],$result2[0]['aqi'],$result1[0]['minimum_temperature']];
// //        $this->success('成功', json_encode($data,JSON_UNESCAPED_UNICODE));
//         $this->success('成功', $data);
//     }

    /**
     * Notes :获取雷达图相关数据
     * @author lichao   2019/5/29
     */
    public function airAllQualityWeather()
    {
        /**
         * 1.获取前6天 + 今天往后7天的预测值
         * 2.判断当前时间的前6天 到 当前时间的前一天 获取实测数据
         * 3.获取当前时间的预测7天的数据
         * 涉及表：
         *      实时天：air_quality_weather_realtime_day        air_quality_station_aqi_realtime_day
         *      预报天：air_quality_weather_forecast_day（左2，右4个值）   air_quality_station_aqi_forecast_day（右2个值）
         * 4.整合数组
         */
        $data = array();
        try {
            $time = strtotime(date('Y-m-d 08:40:00'));
            // 获取当前时间前6天时间
            $sixDaysAgo         = date('Y-m-d 00:00:00', strtotime("-6 day"));
            $beforeDay          = date('Y-m-d 00:00:00', strtotime('-1 day'));   // 当前时间前一天
            $currentTime        = date('Y-m-d 00:00:00');
            $laterTime          = date('Y-m-d 00:00:00', strtotime('+7 day'));
            $weatherPublishTime = date('Y-m-d 00:00:00');
            $stationPublishTime = date('Y-m-d 00:00:00');
            $station_id         = $this->request->param('station_id', 0);

            // 实际数据发布时间取值范围 6天前 -- 当前时间
            // 获取天气实际值
            $weatherRealtimeSql  = "SELECT * FROM `air_quality_weather_realtime_day` WHERE `region_id` = 53 AND 
`publish_time` between ? AND ?";
            $weatherRealtimeData = Db::query($weatherRealtimeSql, array($sixDaysAgo, $beforeDay));
            if (!$weatherRealtimeData) {
                throw new \Exception('获取天气预报实际值失败！');
            }

            // 获取天气预测值 预测数据预测时间取值范围 当前时间为发布时间
            $weatherForecastSql  = "SELECT * FROM `air_quality_weather_forecast_day` WHERE `region_id` = 53 AND 
`predict_time` between ? AND ? AND `publish_time` = ?";
            $weatherForecastData = Db::query($weatherForecastSql, array($currentTime, $laterTime, $weatherPublishTime));
            // if (!$weatherForecastData) {
            //     throw new \Exception('获取天气预报预测值失败！');
            // }
            // 获取站点实测值
            $stationRealtimeSql  = "SELECT * FROM `air_quality_station_aqi_realtime_day` WHERE `region_id` = 53 AND 
`station_id` = ? AND `publish_time` between ? AND ?";
            $stationRealtimeData = Db::query($stationRealtimeSql, array($station_id, $sixDaysAgo, $beforeDay));
            // if (!$stationRealtimeData) {
            //     throw new \Exception('获取站点实测值失败！');
            // }

            // 获取站点预测值
            $stationForecastSql  = "SELECT * FROM `air_quality_station_aqi_forecast_day` WHERE `region_id` = 53 AND 
`station_id` = ? AND `predict_time` between ? AND ? AND `publish_time` = ?";
            $stationForecastData = Db::query($stationForecastSql, array($station_id, $currentTime, $laterTime, $stationPublishTime));
            if (!$stationForecastData) {
                throw new \Exception('获取站点预测值失败！');
            }
            // 获取污染物实测值
            $pollutantRealtimeSql  = "SELECT * FROM `air_quality_station_primary_pollutant_realtime_day` WHERE `region_id` = 53 AND 
`station_id` = ? AND `publish_time` between ? AND ?";
            $pollutantRealtimeData = Db::query($pollutantRealtimeSql, array($station_id, $sixDaysAgo, $beforeDay));
            // if (!$pollutantRealtimeData) {
            //     throw new \Exception('获取污染物实测值失败！');
            // }

            // 获取污染物预测值
            $pollutantForecastSql  = "SELECT * FROM `air_quality_station_primary_pollutant_forecast_day` WHERE `region_id` = 53 AND 
`station_id` = ? AND `predict_time` between ? AND ? AND `publish_time` = ?";
            $pollutantForecastData = Db::query($pollutantForecastSql, array($station_id, $currentTime, $laterTime, $stationPublishTime));
            if (!$pollutantForecastData) {
                throw new \Exception('获取污染物预测值失败！');
            }
            $weatherData   = array_merge_recursive($weatherRealtimeData, $weatherForecastData);
            $stationData   = array_merge_recursive($stationRealtimeData, $stationForecastData);
            $pollutantData = array_merge_recursive($pollutantRealtimeData, $pollutantForecastData);

            // dump($pollutantData);
            // die();

            // 获取系统配置
            $systemSettingSql  = "SELECT * FROM `system_setting` WHERE `region_id` = 53 AND `type` in ('weather', 'station', 'station_alarm')";
            $systemSettingData = Db::query($systemSettingSql);
            if (!$systemSettingData) {
                throw new \Exception('获取系统配置失败！');
            }

            $settingData = array();
            foreach ($systemSettingData as $var) {
                if ($var['type'] == 'weather') {
                    if ($var['name_en'] == 'high_temperature') {
                        $settingData['high_temperature'] = $var['value'];
                    }
                    if ($var['name_en'] == 'low_temperature') {
                        $settingData['low_temperature'] = $var['value'];
                    }
                    if ($var['name_en'] == 'high_wind_power') {
                        $settingData['high_wind_power'] = $var['value'];
                    }
                }
                if ($var['type'] == 'station') {
                    if ($var['name_en'] == 'high_aqi') {
                        $settingData['high_aqi'] = $var['value'];
                    }
                }
                if ($var['type'] == 'station_alarm') {
                    $primaryPollutant = strtoupper($var['name_en']) == 'PM2_5' || strtoupper($var['name_en']) == 'PM25' ? 'PM2.5' : strtoupper($var['name_en']);

                    $settingData['pollutant'][$primaryPollutant] = $var['value'];
                }
            }

            $data = array();
            foreach ($weatherData as $key => $value) {
                $weatherData[$key]['average_wind'] = ($value['average_wind'] >= $settingData['high_wind_power']) ? 16 : $value['average_wind'];
                $weatherPredictTime = isset($value['predict_time']) ? $value['predict_time'] : $value['publish_time'];
                foreach ($stationData as $k => $val) {
                    $stationPredictTime = isset($val['predict_time']) ? $val['predict_time'] : $val['publish_time'];
                    if ($weatherPredictTime == $stationPredictTime) {
                        $year  = substr($weatherPredictTime, 0, 4);
                        $month = substr($weatherPredictTime, 5, 2);
                        $day   = substr($weatherPredictTime, 8, 2);

                        $data[$key]['date']           = ['year' => $year, 'month' => $month, 'day' => $day];
                        $data[$key]['weather']        = ['name' => $value['maximum_sky_condition'], 'icon' => $value['maximum_sky_condition_icon']];
                        $data[$key]['wind_direction'] = $value['wind_direction'];

                        // 处理污染物数据，不一定每天有污染物数据
                        $primaryPollutant = [
                            'name'  => '-',
                            'iaqi' => 0,
                        ];
                        foreach ($pollutantData as $i => $item) {
                            $pollutantPredictTime = isset($item['predict_time']) ? $item['predict_time'] : $item['publish_time'];
                            if ($weatherPredictTime == $pollutantPredictTime) {
                                $primaryPollutant['name']  = strtoupper($item['name']) == 'PM2_5' || strtoupper($item['name']) == 'PM25' ? 'PM2.5' : strtoupper($item['name']);
                                if ($primaryPollutant['name'] == 'O3_8H') {
                                    $primaryPollutant['name'] = 'O3';
                                }
                                $primaryPollutant['iaqi'] = $item['iaqi'];
                            }
                        }
                        $primaryPollutantValue = isset($settingData['pollutant'][$primaryPollutant['name']]) ? $settingData['pollutant'][$primaryPollutant['name']] : '100';
                        $temperature           = round($settingData['high_temperature']) + abs(round($settingData['low_temperature']));
                        if ($primaryPollutant['iaqi'] > 200) {
                            $primaryPollutantValue = $primaryPollutant['iaqi'];
                        }
                        $data[$key]['indicator'] = [
                            ['name' => '最高气温', 'max' => $temperature],
                            ['name' => '最低气温', 'max' => $temperature],
                            ['name' => 'AQI', 'max' => $settingData['high_aqi']],
                            ['name' => '湿度', 'max' => 100],
                            ['name' => $primaryPollutant['name'], 'max' => $primaryPollutantValue],
                            ['name' => '风力', 'max' => $settingData['high_wind_power']],
                        ];

                        if ($value['maximum_temperature'] >= 0) {
                            $maximum_temperature = $value['maximum_temperature'] + abs(round($settingData['low_temperature']));
                        } else {
                            $maximum_temperature = abs($value['maximum_temperature']);
                        }

                        if ($value['minimum_temperature'] >= 0) {
                            $minimum_temperature = $value['minimum_temperature'] + abs(round($settingData['low_temperature']));
                        } else {
                            $minimum_temperature = abs($value['minimum_temperature']);
                        }

                        $data[$key]['data'] = [
                            [
                                'mark'  => [
                                    $value['maximum_temperature'], $value['minimum_temperature'], round($val['aqi']),
                                    $value['average_humidity'], $primaryPollutant['iaqi'], $value['average_wind']],
                                'value' => [
                                    $maximum_temperature, $minimum_temperature, round($val['aqi']),
                                    $value['average_humidity'], $primaryPollutant['iaqi'], $weatherData[$key]['average_wind']],
                                'name'  => '气象分析'
                            ]
                        ];

                    }
                }
            }
            $data = array_values($data);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('获取天气数据成功', $data);
    }

    /**
     * 1.0-2空气质量趋势
     * @author zhugeng 2019-03-21
     */
    public function airQualityTrend()
    {
        $data  = [];
        $param = $this->request->param();
        //日期判断
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //本周
            $todayYearWeek       = self::get_week();
            $param['start_date'] = $todayYearWeek[1];
            $param['end_date']   = $todayYearWeek[7];
        } else {
            $todayYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        }
        if (empty($param['region_id'])) {
            return $this->error('参数错误!');
        }
        $data['date'] = $todayYearWeek;
        $sqlHistory   = 'select aqi,publish_time as pt_time from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        //历史同期数据（去年本周）
        $his_start     = date("Y-m-d", strtotime("-1 year", strtotime($param['start_date'])));
        $his_end       = date("Y-m-d", strtotime("-1 year", strtotime($param['end_date'])));
        $historyResult = Db::query($sqlHistory, array($param['region_id'], $param['station_id'], $his_start, $his_end));
        //预报值
        if (strtotime($param['end_date']) > strtotime(date('Y-m-d', time()))) {
            $sqlForecast1    = 'select aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = predict_time';
            $forecastResult1 = Db::query($sqlForecast1, array($param['region_id'], $param['station_id'], $param['start_date'], date('Y-m-d 00:00:00',strtotime('-1 day'))));
            $sqlForecast2    = 'select aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = ?';
            $forecastResult2 = Db::query($sqlForecast2, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date'].' 00:00:00', date('Y-m-d 00:00:00', time())));
            $forecastResult = array_merge_recursive($forecastResult1,$forecastResult2);
        } else {
            $sqlForecast    = 'select aqi,predict_time as pt_time from air_quality_station_aqi_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ? and publish_time = predict_time';
            $forecastResult = Db::query($sqlForecast, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        }
//        $forecastResult = Db::query($sqlForecast, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        //实际值
        $sqlpractical = 'select aqi,publish_time as pt_time from air_quality_station_aqi_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list         = Db::query($sqlpractical, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        if (count($historyResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][0][] = '';
            }
        } else {
            //历史值数据处理
            $listHistory = [];
            $dateHistory = [];
            foreach ($historyResult as $k => $v) {
                $listHistory[date('m/d', strtotime($v['pt_time']))][] = ceil($v['aqi']);
                array_push($dateHistory, date('m/d', strtotime($v['pt_time'])));
            }
            $dateHistory = array_values(array_unique($dateHistory));//去重，重新排列索引
            foreach ($todayYearWeek as $k => $v) {
                if (in_array($v, $dateHistory)) {
                    $data['data'][0][$k] = $listHistory[$v]['aqi'];
                } else {
                    $data['data'][0][$k] = '';
                }
            }
        }
        if (count($forecastResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][1][] = '';
            }
        } else {
            //预报值数据处理
            $listForecast = [];
            $dateForecast = [];
            foreach ($forecastResult as $k => $v) {
                if (date('H',strtotime($v['pt_time'])) != '12') {
                    $listForecast[date('m/d', strtotime($v['pt_time']))][] = ceil($v['aqi']);
                    array_push($dateForecast, date('m/d', strtotime($v['pt_time'])));
                }
            }
            $dateForecast = array_values(array_unique($dateForecast));//去重，重新排列索引
            foreach ($todayYearWeek as $k => $v) {
                if (in_array($v, $dateForecast)) {
                    $data['data'][1][$k] = $listForecast[$v][0];
                } else {
                    $data['data'][1][$k] = '';
                }
            }
        }
        //处理实际值
        if (count($list) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][2][] = '';
            }
        } else {
            //相差天数
            $listReal = [];
            $dateReal = [];
            foreach ($list as $k => $v) {
                if (date('H',strtotime($v['pt_time'])) != '12') {
                    $listReal[date('m/d', strtotime($v['pt_time']))][] = ceil($v['aqi']);
                    array_push($dateReal, date('m/d', strtotime($v['pt_time'])));
                }

            }
            $dateReal = array_values(array_unique($dateReal));//去重，重新排列索引
            foreach ($todayYearWeek as $k => $v) {
                if (in_array($v, $dateReal)) {
                    $data['data'][2][$k] = $listReal[$v][0];
                } else {
                    $data['data'][2][$k] = '';
                }
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 1.0-3首要污染物
     * @author zhugeng 2019-03-21
     */
    public function chieflyPollutant()
    {
        $data = [];
        //本周
        $param = $this->request->param();
        //日期判断
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //本周
            $todayYearWeek       = self::get_week();
            $param['start_date'] = $todayYearWeek[1];
            $param['end_date']   = $todayYearWeek[7];
        } else {
            $todayYearWeek = self::getDateFromRange($param['start_date'], $param['end_date']);
        }
        if (empty($param['region_id'])) {
            return $this->error('参数错误!');
        }

        $data['date'] = $todayYearWeek;
        $sqlHistory   = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        //历史同期数据（去年本周）
        $his_start     = date("Y-m-d", strtotime("-1 year", strtotime($param['start_date'])));
        $his_end       = date("Y-m-d", strtotime("-1 year", strtotime($param['end_date'])));
        $historyResult = Db::query($sqlHistory, array($param['region_id'], $param['station_id'], $his_start, $his_end));
        $num = 1;
        $num1 = 2;
        if (count($historyResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][0][] = ['name' => '', 'value' => '', 'type' => 1];
            }
        } else {
            //历史值数据处理
//            $data['historical'] = [];
            $newList1 = [];
            foreach ($historyResult as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                $newList1[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
            }
            foreach ($newList1 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i=0;$i<count($v1);$i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList1[$k1],$i,1);//删除数组元素，索引重组
                        }
                    }
                }

            }
            $temp = [];
            foreach ($newList1 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num = max($temp);
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($newList1); $k++) {
                    if (!isset($newList1[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$j][] = ['name' => '', 'value' => '', 'type' => 1];
                    } else {
                        if (strtoupper($newList1[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList1[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$j][] = ['name' => strtoupper($newList1[$todayYearWeek[$k]][$j]['name']), 'value' => $newList1[$todayYearWeek[$k]][$j]['value'], 'type' => 1];
                    }
                }
            }
        }
        if (strtotime($param['end_date']) < strtotime(date('Y-m-d',time()))) {
            //实际
            $sql_forecast_over = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and predict_time = publish_time";
            $forecastResult = Db::query($sql_forecast_over, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        } else {
            //预报
            $sql_forecast_over1 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = predict_time";
            $forecastResult1 = Db::query($sql_forecast_over1, array($param['region_id'], $param['station_id'], $param['start_date'].' 00:00:00', date("Y-m-d 00:00:00", strtotime("-1 day"))));
            //预报
            $sql_forecast_over2 = "select predict_time as dt_time,name,value from air_quality_station_primary_pollutant_forecast_day where region_id = ? and station_id = ? and predict_time between ? and ?  and publish_time = ?";
            $forecastResult2 = Db::query($sql_forecast_over2, array($param['region_id'], $param['station_id'],date('Y-m-d 00:00:00',time()), $param['end_date'].' 00:00:00',date('Y-m-d',time())));
            $forecastResult = array_merge_recursive($forecastResult1,$forecastResult2);
        }

        if (count($forecastResult) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][1][] = ['name' => '', 'value' => '', 'type' => 2];
            }
        } else {
            $newList2 = [];
            foreach ($forecastResult as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                if (date('H',strtotime($v['dt_time'])) == '12') {
                    array_splice($forecastResult,$k,1);//删除数组元素，索引重组
                } else {
                    $newList2[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
                }

            }
            foreach ($newList2 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i=0;$i<count($v1);$i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
                        }
//                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3') {
//                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
//                        }
//                        if (strtoupper($v2['name']) == 'O3_8H' && strtoupper($v1[$i]['name']) == 'O3_8H') {
//                            array_splice($newList2[$k1],$i,1);//删除数组元素，索引重组
//                        }
                    }
                }
            }
            $temp = [];
            foreach ($newList2 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            $num1 = $num + max($temp);
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($todayYearWeek); $k++) {
                    if (!isset($newList2[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$num+$j][] = ['name' => '', 'value' => '', 'type' => 2];
                    } else {
                        if (strtoupper($newList2[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList2[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$num+$j][] = ['name' => strtoupper($newList2[$todayYearWeek[$k]][$j]['name']), 'value' => $newList2[$todayYearWeek[$k]][$j]['value'], 'type' => 2];
                    }
                }
            }
        }

        //实际值
        $sqlpractical = 'select publish_time as dt_time,name,value from air_quality_station_primary_pollutant_realtime_day where region_id = ? and station_id = ? and publish_time between ? and ?';
        $list         = Db::query($sqlpractical, array($param['region_id'], $param['station_id'], $param['start_date'], $param['end_date']));
        if (count($list) <= 0) {
            foreach ($todayYearWeek as $k => $v) {
                $data['data'][2][] = ['name' => '', 'value' => '', 'type' => 3];
            }
        } else {
            $newList3 = [];
            foreach ($list as $k => $v) {
                if ($v['name'] == 'CO') {
                    $v['value'] = round($v['value'], 1);
                } else {
                    $v['value'] = round($v['value']);
                }
                $newList3[date("m/d", strtotime($v['dt_time']))][] = ['name' => $v['name'], 'value' => $v['value']];
            }
            foreach ($newList3 as $k1 => $v1) {
                //处理O3和O3_8H
                for ($i=0;$i<count($v1);$i++) {
                    foreach ($v1 as $k2 => $v2) {
                        if (strtoupper($v2['name']) == 'O3' && strtoupper($v1[$i]['name']) == 'O3_8H') {
                            array_splice($newList3[$k1],$i,1);//删除数组元素，索引重组
                        }
                    }
                }

            }
            $temp = [];
            foreach ($newList3 as $k1 => $v1) {
                $temp[$k1] = count($v1);
            }
            for ($j = 0; $j < max($temp); $j++) {
                for ($k = 0; $k < count($todayYearWeek); $k++) {
                    if (!isset($newList3[$todayYearWeek[$k]][$j]['name'])) {
                        $data['data'][$num1+$j][] = ['name' => '', 'value' => '', 'type' => 3];
                    } else {
                        if (strtoupper($newList3[$todayYearWeek[$k]][$j]['name']) == 'O3_8H') {
                            $newList3[$todayYearWeek[$k]][$j]['name'] = 'O3';
                        }
                        $data['data'][$num1+$j][] = ['name' => strtoupper($newList3[$todayYearWeek[$k]][$j]['name']), 'value' => $newList3[$todayYearWeek[$k]][$j]['value'], 'type' => 3];
                    }
                }
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 贡献度趋势图
     * @author zhugeng 2019-03-25
     */
    public function contributionTrend()
    {
        //链接MongoDB数据库（远程）
        $PDOManager = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        //本地
        //$this->PDOManager = new \MongoDB\Driver\Manager("mongodb://localhost:27017");
        $PDOBulk = new \MongoDB\Driver\BulkWrite;//插入
        $opt     = [
            'projection' => [],
        ];
        $param   = $this->request->param();
        //日期判断
        if (!isset($param['start_date']) && !isset($param['end_date'])) {
            //本周
            $beforDate           = self::get_week();
            $param['start_date'] = $beforDate[1];
            $param['end_date']   = $beforDate[7];
        } else {
            $beforDate = self::getDateFromRange($param['start_date'], $param['end_date']);
        }
        $data         = [];
        $data['date'] = $beforDate;

        //条件参数
        $map = [
            "region_id"    => (int)$param['region_id'],
            "industry_id"  => $param['industry_id'],
            "publish_time" => ['$gte' => $param['start_date'], '$lte' => $param['end_date']],
            '$where'       => 'this.publish_time == this.predict_time'
        ];
        // 1工业、2非工业
        if ($param['industry_id'] == 1) {
            $map['industry_id'] = ['$in' => Config::get('industry_limit_arr_mongodb')];
        } else {
            $map['industry_id'] = ['$in' => [8, 9, 10, 11]];
        }
        $query  = new \MongoDB\Driver\Query($map, $opt);//查询
        $cursor = $PDOManager->executeQuery('huanxin.air_quality_pollutant_station_forecast_day', $query)->toArray();
        $list   = json_decode(json_encode($cursor), true);

        if (count($list) <= 0) {
            foreach ($beforDate as $k => $v) {
                $data['data'][0][] = '';
                $data['data'][1][] = '';
                $data['data'][2][] = '';
            }
        } else {
            foreach ($beforDate as $k => $v) {
                foreach ($list as $k1 => $v1) {
                    if ($v == date('m/d', strtotime($v1['publish_time']))) {
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'PM2_5') {
                            $data['data'][0][] = $v1['contribution_value'];
                        }
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'SO2') {
                            $data['data'][1][] = $v1['contribution_value'];
                        }
                        if (isset($v1['contribution_name']) && $v1['contribution_name'] == 'NO2') {
                            $data['data'][2][] = $v1['contribution_value'];
                        }
                    }
                }
            }
        }
        $this->success('成功', $data);
    }

    /**
     * 首页报警提示
     * zhugeng 2019-04-19
     */
//    public function alarmNews()
//    {
//        $param = $this->request->param();
//        if (empty($param['region_id'])) {
//            return $this->error('');
//        }
//        $sql = 'select * from alarm_news where region_id = ?';
//        $list = Db::query($sql,$param['region_id']);
//        if (count($list) <= 0) {
//            return $this->success('暂无数据');
//        }
//        $data['站点报警'] = [];
//        $data['工况报警'] = [];
//        $data['重污染报警'] = [];
//        foreach ($list as $k => $v) {
//            if ($v['alarm_type'] == '站点报警') {
//                artay_push($data['站点报警'],$v);
//            } else if($v['alarm_type'] == '工况报警') {
//                artay_push($data['工况报警'],$v);
//            } else {
//                artay_push($data['重污染报警'],$v);
//            }
//        }
//        $this->success('成功', $data);
//    }

    /**
     * @author zhugeng 2019-05-07
     * @param $day1 开始日期
     * @param $day2 结束日期
     * @return float|int 相差天数
     */
    function diffBetweenTwoDays ($day1, $day2)
    {
        $second1 = strtotime($day1);
        $second2 = strtotime($day2);

        if ($second1 < $second2) {
            $tmp = $second2;
            $second2 = $second1;
            $second1 = $tmp;
        }
        return ($second1 - $second2) / 86400;
    }
    /**
     * 获取本周所有日期
     */
    function get_week($time = '', $format = 'm/d')
    {
        $time = $time != '' ? $time : time();
        //获取当前周几
        $week = date('w', $time);
        $date = [];
        for ($i = 1; $i <= 7; $i++) {
            $date[$i] = date($format, strtotime('+' . $i - $week . ' days', $time));
        }
        return $date;
    }

    /**
     * 获取指定日期段内每一天的日期
     * @param Date $startdate 开始日期
     * @param Date $enddate 结束日期
     * @return Array
     */
    function getDateFromRange($startdate, $enddate)
    {
        $stimestamp = strtotime($startdate);
        $etimestamp = strtotime($enddate);
        // 计算日期段内有多少天
        $days = ($etimestamp - $stimestamp) / 86400 + 1;
        // 保存每天日期
        $date = array();
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('m/d', $stimestamp + (86400 * $i));
        }
        return $date;
    }

    /**
     * 获取今天之前（不包含今天）七天所有日期
     */
    function get_last_weeks($time = '', $format = 'm/d')
    {
        $time = $time != '' ? $time : time();
        //组合数据
        $date = [];
        for ($i = 1; $i <= 7; $i++) {
            //不包含今天，如果要算今天的话   $i-7
            $date[$i] = date($format, strtotime('+' . $i - 8 . 'days', $time));
        }
        return $date;
    }
}